{{!
  Copyright (c) Meta Platforms, Inc. and affiliates.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

}}{{!

    NOTE:
    Unfortunately map literals cannot be used to store metadata, due to a bug
    in the Go compiler: https://github.com/golang/go/issues/33437
    The bug results in a "NewBulk too big" compilation error for some very large schemas.
    The workaround is to create slice literals (one with keys, one with values),
    create an empty map during runtime and populate that map from the two slices.

}}{{> common/header}}

import (
    {{#program:thrift_imports}}
    {{program:go_package_alias}} "{{program:go_import_path}}"
    {{/program:thrift_imports}}
    thrift "{{program:thrift_lib_import}}"
    {{#program:import_metadata_package?}}
    metadata "{{program:thrift_metadata_import}}"
    {{/program:import_metadata_package?}}
)

// mapsCopy is a copy of maps.Copy from Go 1.21
// TODO: remove mapsCopy once we can safely upgrade to Go 1.21 without requiring any rollback.
func mapsCopy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2) {
	for k, v := range src {
		dst[k] = v
	}
}

{{> common/unused_imports_protection}}
// (needed to ensure safety because of naive import list construction)
var _ = thrift.ZERO
// TODO: uncomment when can safely upgrade to Go 1.21 without requiring any rollback.
// var _ = maps.Copy[map[int]int, map[int]int]
{{#program:import_metadata_package?}}
var _ = metadata.GoUnusedProtection__
{{/program:import_metadata_package?}}

// Premade Thrift types
var (
    {{#program:thrift_metadata_types}}
    {{type:metadata_name}} = {{program:metadata_qualifier}}NewThriftType().{{> metadata/thrift_type_setter}}(
        {{> metadata/thrift_type_instance}}
    )
    {{/program:thrift_metadata_types}}
)

var structMetadatas = []*{{program:metadata_qualifier}}ThriftStruct{
    {{#program:structs}}
    {{^struct:exception?}}
    {{> metadata/thrift_metadata_struct}},
    {{/struct:exception?}}
    {{/program:structs}}
}

var exceptionMetadatas = []*{{program:metadata_qualifier}}ThriftException{
    {{#program:structs}}
    {{#struct:exception?}}
    {{> metadata/thrift_metadata_exception}},
    {{/struct:exception?}}
    {{/program:structs}}
}

var enumMetadatas = []*{{program:metadata_qualifier}}ThriftEnum{
    {{#program:enums}}
    {{> metadata/thrift_metadata_enum}},
    {{/program:enums}}
}

var serviceMetadatas = []*{{program:metadata_qualifier}}ThriftService{
    {{#program:services}}
    {{> metadata/thrift_metadata_service}},
    {{/program:services}}
}

// GetThriftMetadata returns complete Thrift metadata for current and imported packages.
func GetThriftMetadata() *{{program:metadata_qualifier}}ThriftMetadata {
    allEnums := GetEnumsMetadata()
    allStructs := GetStructsMetadata()
    allExceptions := GetExceptionsMetadata()
    allServices := GetServicesMetadata()

    return {{program:metadata_qualifier}}NewThriftMetadata().
        SetEnums(allEnums).
        SetStructs(allStructs).
        SetExceptions(allExceptions).
        SetServices(allServices)
}

// GetEnumsMetadata returns Thrift metadata for enums in the current and recursively included packages.
func GetEnumsMetadata() map[string]*{{program:metadata_qualifier}}ThriftEnum {
    allEnumsMap := make(map[string]*{{program:metadata_qualifier}}ThriftEnum)

    // Add enum metadatas from the current program...
    for _, enumMetadata := range enumMetadatas {
        allEnumsMap[enumMetadata.GetName()] = enumMetadata
    }

    // ...now add enum metadatas from recursively included programs.
    {{#program:thrift_imports}}
    mapsCopy(allEnumsMap, {{program:go_package_alias}}.GetEnumsMetadata())
    {{/program:thrift_imports}}

    return allEnumsMap
}

// GetStructsMetadata returns Thrift metadata for structs in the current and recursively included packages.
func GetStructsMetadata() map[string]*{{program:metadata_qualifier}}ThriftStruct {
    allStructsMap := make(map[string]*{{program:metadata_qualifier}}ThriftStruct)

    // Add struct metadatas from the current program...
    for _, structMetadata := range structMetadatas {
        allStructsMap[structMetadata.GetName()] = structMetadata
    }

    // ...now add struct metadatas from recursively included programs.
    {{#program:thrift_imports}}
    mapsCopy(allStructsMap, {{program:go_package_alias}}.GetStructsMetadata())
    {{/program:thrift_imports}}

    return allStructsMap
}

// GetExceptionsMetadata returns Thrift metadata for exceptions in the current and recursively included packages.
func GetExceptionsMetadata() map[string]*{{program:metadata_qualifier}}ThriftException {
    allExceptionsMap := make(map[string]*{{program:metadata_qualifier}}ThriftException)

    // Add exception metadatas from the current program...
    for _, exceptionMetadata := range exceptionMetadatas {
        allExceptionsMap[exceptionMetadata.GetName()] = exceptionMetadata
    }

    // ...now add exception metadatas from recursively included programs.
    {{#program:thrift_imports}}
    mapsCopy(allExceptionsMap, {{program:go_package_alias}}.GetExceptionsMetadata())
    {{/program:thrift_imports}}

    return allExceptionsMap
}

// GetServicesMetadata returns Thrift metadata for services in the current and recursively included packages.
func GetServicesMetadata() map[string]*{{program:metadata_qualifier}}ThriftService {
    allServicesMap := make(map[string]*{{program:metadata_qualifier}}ThriftService)

    // Add service metadatas from the current program...
    for _, serviceMetadata := range serviceMetadatas {
        allServicesMap[serviceMetadata.GetName()] = serviceMetadata
    }

    // ...now add service metadatas from recursively included programs.
    {{#program:thrift_imports}}
    mapsCopy(allServicesMap, {{program:go_package_alias}}.GetServicesMetadata())
    {{/program:thrift_imports}}

    return allServicesMap
}

// GetThriftMetadataForService returns Thrift metadata for the given service.
func GetThriftMetadataForService(scopedServiceName string) *{{program:metadata_qualifier}}ThriftMetadata {
    thriftMetadata := GetThriftMetadata()

    allServicesMap := thriftMetadata.GetServices()
    relevantServicesMap := make(map[string]*{{program:metadata_qualifier}}ThriftService)

    serviceMetadata := allServicesMap[scopedServiceName]
    // Visit and record all recursive parents of the target service.
    for serviceMetadata != nil {
        relevantServicesMap[serviceMetadata.GetName()] = serviceMetadata
        if serviceMetadata.IsSetParent() {
            serviceMetadata = allServicesMap[serviceMetadata.GetParent()]
        } else {
            serviceMetadata = nil
        }
    }

    thriftMetadata.SetServices(relevantServicesMap)

    return thriftMetadata
}
